package com.longtop.leaning.serializable;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import com.longtop.leaning.entity.User;

public class UserSerializable extends BaseSerializable {

	private static final UserSerializable instance = new UserSerializable();

	private UserSerializable() {
	}

	public static UserSerializable getInstance() {
		return instance;
	}

	public Object deserialize(byte[] data) {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		DataInputStream dis = new DataInputStream(bais);
		User result = new User();
		try {
			result.setLoginid(dis.readUTF());
			result.setPasswd(dis.readUTF());

			dis.close();
			bais.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("--------------反序列化出错-------------------" + e);
		}
		return result;
	}

	public byte[] serialize(Object obj) {
		User user = (User) obj;
		this.checkObjValue(obj);
		byte[] ret = null;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		try {
			dos.writeUTF(user.getLoginid());
			dos.writeUTF(user.getPasswd());

			ret = baos.toByteArray();

			dos.close();
			baos.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("--------------序列化出错-------------------" + e);
		}
		return ret;
	}

	public void checkObjValue(Object obj) {
		User user = (User) obj;
		if (user.getLoginid() == null) {
			user.setLoginid("");
		}
		if (user.getPasswd() == null) {
			user.setPasswd("");
		}
	}

}
